﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel.Composition;
using AvalonDock;
using System.Xml.Linq;
using System.IO;
using Microsoft.Practices.ServiceLocation;
using System.Windows.Media;

namespace DynamicUIFramework
{
    [Export]
    public class RegionContent : DockableContent
    {
        public RegionContent(string name)
        {
            this.Name = name;
            if (this.Content != null)
            {
                (this.Content as Panel).Background = this.Background;
            }
        }

        public override void SaveLayout(System.Xml.XmlWriter storeWriter)
        {
            base.SaveLayout(storeWriter);

            XElement ele = Save();
            ele.Save(Path.Combine(UISetting.RegionPath, (this.Name + ".xml")));
        }

        public XElement Save()
        {
            XElement ele = new XElement("Region");
            ele.SetAttributeValue("name", this.Name);
            ele.SetAttributeValue("title", this.Title);
            IPanel panel = this.Content as IPanel;
            if (panel != null)
                ele.Add((this.Content as IPanel).Save());
            return ele;
        }

        public override void RestoreLayout(System.Xml.XmlElement contentElement)
        {
            base.RestoreLayout(contentElement);
            Load();
        }

        public void Load()
        {
            RegionController rc = ServiceLocator.Current.GetInstance<RegionController>();
            XElement ele = rc.GetRegionElement(this.Name);
            if (ele != null)
            {
                this.Title = ele.Attribute("title").Value;

                XElement panelElement = ele.Elements().First();
                string target = panelElement.Attribute("target").Value;
                IPanel panel = Activator.CreateInstance(this.GetType().Assembly.GetType(target)) as IPanel;
                this.Content = panel;
                panel.Load(panelElement);
            }
        }
    }
}
